// 规范本地缓存写法
import { resolve } from "path";
import * as fs from "fs";
import { StorageKey } from "./StorageKey";

/**
 * Electron本地文件缓存
 */
class ElectronStore {
  /**
   * 缓存目录
   */
  dirPath = ""; // resolve(remote.app.getPath('userData'), './localStorage')

  setDirPath(dirPath: string) {
    this.dirPath = dirPath;
    if (!fs.existsSync(this.dirPath)) {
      fs.mkdirSync(this.dirPath);
    }
  }

  /**
   * 读取文件内容
   * @param key
   * @returns
   */
  getItem(key: string): string | null {
    const result = this.readStore(key);
    if (result === undefined || result === null) return null;
    return result;
  }

  /**
   * 写入文件内容，不存在则创建，已存在则覆盖
   * @param key
   * @param str
   */
  setItem(key: string, str: string): void {
    const filePath = resolve(this.dirPath, key);

    fs.writeFileSync(filePath, str);
  }

  /**
   * 删除文件
   * @param key
   */
  removeItem(key: string): void {
    const filePath = resolve(this.dirPath, key);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
  }

  /**
   * 读取文件
   * @param key
   * @returns
   */
  readStore(key: string): string | undefined {
    const filePath = resolve(this.dirPath, key);
    if (!fs.existsSync(filePath)) return undefined;
    const dataStr = fs.readFileSync(filePath, "utf-8");
    return dataStr;
  }
}
/**
 * 适配多种缓存模式，当前只考虑文件缓存，如果要做web端，则要切换为LocalStorage缓存
 */
export class StorageManager {
  prefix: string;
  store = new ElectronStore();

  constructor(option: { prefix?: string } = {}) {
    const { prefix = "m-design" } = option;
    this.prefix = prefix;
  }
  private formatKey(key = ""): string {
    return `${this.prefix}-${key}`;
  }

  /**
   * 设置缓存，注意val会被json化，不能存储Symbol和循环引用的对象
   * @param key 保存的键值
   * @param val 保存的内容
   * @param storageType
   */
  set(key: StorageKey, val: any) {
    if (val === undefined) {
      val = null;
    }
    const key2 = this.formatKey(key);
    this.store.setItem(key2, JSON.stringify(val));
  }
  /**
   * 获取缓存
   * @param  {[String]} key 获取的键值
   * @param storageType
   * @return {Object}
   */
  get(key: StorageKey) {
    const key2 = this.formatKey(key);
    try {
      const str = this.store.getItem(key2);
      if (str !== "undefined") {
        return str && JSON.parse(str);
      }
    } catch (e) {
      console.error(e);
      return null;
    }
  }
  /**
   * 删除缓存
   * @param  {String} key 删除的键值
   * @param storageType
   */
  remove(key: StorageKey) {
    const key2 = this.formatKey(key);
    this.store.removeItem(key2);
  }
}
